package com.xjx.account.algorithm;

import com.xjx.common.util.ConsistentHashUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.List;

@Slf4j
public class ConsistentHashShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
    
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        // 将可用目标名称转换为列表
        List<String> targetNames = (List<String>) availableTargetNames;
        
        // 初始化一致性哈希环（如果未初始化）
        if (ConsistentHashUtil.getAllNodes().isEmpty()) {
            ConsistentHashUtil.initHashRing(targetNames);
        }
        
        // 获取分片键值
        Long shardingKey = shardingValue.getValue();
        
        // 使用一致性哈希算法获取目标节点
        String targetNode = ConsistentHashUtil.getNode(shardingKey);
        
        log.debug("分片键: {}, 目标节点: {}", shardingKey, targetNode);
        
        return targetNode;
    }
}
